import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import { Link } from 'react-router-dom';
import welcomeStyle from './welcome.scss';

import ContentLayout from '@/component/common/ContentLayout';
import WithdrawWrap from '@/component/welcome/withdrawWrap';

import * as echarts from 'echarts/src/echarts';
import 'echarts/src/component/tooltip';
import 'echarts/src/component/title';
import 'echarts/src/chart/pie';
import 'echarts/src/component/legend';
import 'echarts/src/chart/bar';
import 'echarts/src/chart/line';

import ApiHelper from '@/store/ApiHelper';
import { alliance_chart, message_new } from '@/constants/ApiTypes';
import adminType from '@/tool/adminType';
import adminAuthType from '@/tool/adminAuthType';
import authCheck from '@/tool/authCheck';
import MModal from "@/component/common/MModal";
import ConfigStore from '@/store/Config';

const mConfirm = MModal.confirm;

class PieItem extends Component {
    static propTypes = {
        caption: PropTypes.string.isRequired,
        legend: PropTypes.array.isRequired,
        data: PropTypes.array.isRequired,
        unit: PropTypes.string
    };
    static defaultPropTypes = {
        unit: ''
    };
    componentDidMount() {
        const { caption, legend, data, unit } = this.props;
        let chart = echarts.init(this.ele);
        let option = {
            backgroundColor: '',
            legend: {
                orient: 'horizontal',
                bottom: 'top',
                left: 'center',
                data: legend,
                textStyle: {
                    fontSize: 14,
                    fontWeight: 300
                },
                formatter: function (name) {
                    return name;
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c}" + unit + " ({d}%)"
            },
            series: [
                {
                    name: caption,
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '50%'],
                    selectedMode: 'single',
                    data,
                    label: {
                        normal: {
                            textStyle: {
                                color: 'rgba(0, 0, 0, 0.3)'
                            }
                        }
                    },
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ],
            color: ['#4cc6ff', '#9fd569', '#ffaaf1']
        };

        chart.setOption(option);

        this.chart = chart;
    }
    render() {
        const { caption } = this.props;
        return (
            <div className={welcomeStyle['pie-item']}>
                <h2>{caption}</h2>
                <div className={welcomeStyle['pie-item-wrap']} ref={ div => this.ele = div } />
            </div>
        );
    }
}

class BarItem extends Component {
    static propTypes = {
        source: PropTypes.object.isRequired
    };
    componentDidMount() {
        const { source } = this.props;
        let chart = echarts.init(this.ele);
        let option = {
            color: ['#3398DB'],
            tooltip: {
                trigger: 'axis',
                axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                },
                formatter: "{a}: {c}元"
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    data: source.xAxis,
                    axisTick: {
                        alignWithLabel: true
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    axisLabel: {
                        formatter: '{value} 元'
                    }
                }
            ],
            series: [
                {
                    name: '预期收入',
                    type: 'bar',
                    barWidth: '60%',
                    data: source.data
                }
            ]
        };

        chart.setOption(option);

        this.chart = chart;
    }
    render() {
        return (
            <div className={welcomeStyle['chart-item']}>
                <span>预期月待收房租直方图</span>
                <div className={welcomeStyle['chart-item-wrap']} ref={ div => this.ele = div } />
            </div>
        );
    }
}

class LineItem extends Component {
    static propTypes = {
        source: PropTypes.object.isRequired
    };
    componentDidMount() {
        const { source } = this.props;
        let chart = echarts.init(this.ele);
        let option = {
            tooltip: {
                trigger: 'axis',
                formatter: "{a}: {c}元"
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: source.xAxis
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value} 元'
                }
            },
            series: [
                {
                    name: '历史收入',
                    type: 'line',
                    stack: '总量',
                    data: source.data
                }
            ],
            color: ['#FFBC02']
        };

        chart.setOption(option);

        this.chart = chart;
    }
    render() {
        return (
            <div className={welcomeStyle['chart-item']}>
                <span>利润趋势图</span>
                <div className={welcomeStyle['chart-item-wrap']} ref={ div => this.ele = div } />
            </div>
        );
    }
}

class MessageWedgit extends Component {
    constructor(props) {
        super(props);
    }
    state = {
        msg: null
    };
    getMessageNew = async () => {
        const result = await ApiHelper.requestPost(message_new);
        if (result.status) {
            this.setState({ msg: result.info });
        }
        this.timer = setTimeout(this.getMessageNew, 5000); //5秒
    };
    componentDidMount() {
        this.getMessageNew();
    }
    componentWillUnmount() {
        clearTimeout(this.timer);
    }
    render() {
        const { msg } = this.state;
        if (msg == null) return null;
        const type_name = ['系统消息', '房租消息', '合同消息', '预期消息'];
        return (
            <div className={welcomeStyle['message-wedgit']}>
                <div className={welcomeStyle['inner']}>
                    <span className={welcomeStyle['message-wedgit-type']}><img src="/static/alliance2/image/welcome/xiaolaba.png" />{type_name[msg.type]}：</span>
                    <span>{msg.content}</span>
                </div>
            </div>
        );
    }
}

@observer class Welcome extends Component {
    state = {
        loading: true,
        chartData: {
            house_nsign: 0, //发布中
            house_sign: 0, //已签合同
            overdue_rent: 0, //逾期房租
            rent_will_pay: 0 //待收房租
        }
    };
    async componentDidMount() {
        this._isMounted = true;
        //获取首页图表数据
        const result = await ApiHelper.requestPost(alliance_chart);
        if (!result.status) return;
        this.setState({
            loading: false,
            chartData: result.info
        });
        if (process.env.NODE_ENV === 'production' && adminAuthType() == 1 && !ConfigStore.get('SWITCH-OLD-VERSION')) {
            ConfigStore.set('SWITCH-OLD-VERSION', true);
            mConfirm({
                title: '是否切换回旧版管理后台？',
                titleStyle: { fontSize: 16 },
                width: 300,
                height: 177,
                content: '',
                okText: '是',
                cancelText: '否',
                okClassName: 'primary-btn-ok',
                cancelClassName: 'primary-btn-cancel',
                showTopClose: false,
                onOk() {
                    window.location.href = 'http://alliance.91renta.com';
                },
                onCancel() {}
            });
        }
    }
    componentWillUnmount() {
        this._isMounted = false;
    }
    render() {
        const { chartData } = this.state;
        const _chartData1 = [
            { name: '发布中', value: chartData.house_nsign },
            { name: '已签合同', value: chartData.house_sign }
        ];
        const _chartData2 = [
            { name: '待收房租', value: chartData.rent_will_pay / 100 },
            { name: '欠租逾期', value: chartData.overdue_rent / 100 }
        ];
        const _chartData3 = [
            { name: '智能锁房源', value: chartData.house_lock },
            { name: '其他房源', value: chartData.house_nlock }
        ];

        const _getData = targetData => {
            let __charData = {
                xAxis: [],
                data: []
            };
            for (let key in targetData) {
                if (targetData.hasOwnProperty(key)) {
                    __charData.xAxis.push(key);
                    __charData.data.push(targetData[key] / 100);
                }
            }
            return __charData;
        };

        let _charData4 = _getData(chartData.rent_will_pay_list);
        let _charData5 = _getData(chartData.before_profit);

        return (
            <ContentLayout loading={this.state.loading}>
                <div className={welcomeStyle['welcome-wrap']}>
                    {adminType() == 1 && <WithdrawWrap />}
                    <div className={welcomeStyle['pie-wrap']}>
                        <PieItem caption="出租比" legend={['发布中', '已签合同']} unit="套" data={_chartData1}/>
                        <PieItem caption="待收房租" legend={['待收房租', '欠租逾期']} unit="元" data={_chartData2}/>
                        <PieItem caption="智能锁" legend={['其他房源', '智能锁房源']} unit="套" data={_chartData3}/>
                        <div className={welcomeStyle['operator-btn-group']} >
                            {authCheck('*', '房源') &&
                            <Link className={welcomeStyle['operator-btn']} to="/房源/录入房源">录入房源</Link>}
                            {authCheck('*', '财务') &&
                            <Link className={welcomeStyle['operator-btn']} to="/财务">交易流水</Link>}
                        </div>
                    </div>
                    <div className={welcomeStyle['chart-wrap']}>
                        <BarItem source={_charData4}/>
                        <div className={welcomeStyle['chart-operator']}>
                            <a href="javascript:void(0);"><span style={{ backgroundColor: '#3eb07a' }} />历史预期</a>
                            <a href="javascript:void(0);"><span style={{ backgroundColor: '#ee9234' }} />未来预期</a>
                        </div>
                        <LineItem source={_charData5}/>
                        <div className={welcomeStyle['chart-operator']}>
                            <a href="javascript:void(0);"><span style={{ backgroundColor: '#3eb07a' }} />历史预期</a>
                            <a href="javascript:void(0);"><span style={{ backgroundColor: '#ee9234' }} />未来预期</a>
                        </div>
                    </div>
                    <MessageWedgit/>
                </div>
            </ContentLayout>
        );
    }
}

export default Welcome;